#region The MIT License
// The MIT License
// 
// Copyright (c) 2009 octalforty studios
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Xml;
using octalforty.Componento.Shared.SemanticModel;

namespace octalforty.Componento.Shared.Util
{
    public class ComponentDescriptorParser
    {
        private readonly XmlNamespaceManager namespaceManager;

        public ComponentDescriptorParser()
        {
            namespaceManager = new XmlNamespaceManager(new NameTable());
            namespaceManager.AddNamespace("componento", "http://schemas.componento.net/1.0/components.xsd");
        }

        public ComponentDescriptor[] ParseComponentDescriptors(XmlDocument xmlDocument)
        {
            return ParseComponentDescriptors(xmlDocument.SelectNodes("/componento:components/componento:component", namespaceManager));
        }

        public ComponentDescriptor[] ParseComponentDescriptors(XmlNodeList xmlNodes)
        {
            List<ComponentDescriptor> repositoryEntries = new List<ComponentDescriptor>();

            foreach(XmlNode componentNode in xmlNodes)
            {
                ComponentDescriptor componentDescriptor = ParseComponentDescriptor(componentNode);
                repositoryEntries.Add(componentDescriptor);
            } // foreach

            return repositoryEntries.ToArray();
        }

        public ComponentDescriptor ParseComponentDescriptor(XmlNode xmlNode)
        {
            return ParseComponentDescriptor(xmlNode, namespaceManager);
        }

        public ComponentDescriptor ParseComponentDescriptor(XmlNode xmlNode, XmlNamespaceManager xmlNamespaceManager)
        {
            string name = xmlNode.Attributes["name"].Value;

            Version version = XmlParserUtil.ParseAttributeValue<Version>(
                xmlNode.Attributes["version"],
                delegate(string s) { return new Version(s); });

            Uri manifestUri = XmlParserUtil.ParseUri(xmlNode.Attributes["manifest-uri"]);
            Uri projectUri = XmlParserUtil.ParseUri(xmlNode.Attributes["project-uri"]);
            Uri projectLogoUri = XmlParserUtil.ParseUri(xmlNode.Attributes["project-logo-uri"]);

            XmlNode descriptionNode = xmlNode.SelectSingleNode("componento:description", xmlNamespaceManager);
            string description = descriptionNode == null ?
                                                             null :
                                                                      descriptionNode.ChildNodes[0].NodeType == XmlNodeType.CDATA ?
                                                                                                                                      descriptionNode.ChildNodes[0].InnerText :  
                                                                                                                                                                                  descriptionNode.InnerText;

            return new ComponentDescriptor(name, version, manifestUri, projectUri, projectLogoUri, 
                                           description, ParseClis(xmlNode, xmlNamespaceManager), ParseIsas(xmlNode, xmlNamespaceManager), 
                                           ParseLicenses(xmlNode, xmlNamespaceManager));
        }

        private CliEnvironment[] ParseClis(XmlNode componentNode, XmlNamespaceManager xmlNamespaceManager)
        {
            return XmlParserUtil.Parse<CliEnvironment>(componentNode, "componento:clis/componento:cli", xmlNamespaceManager, 
                                                       delegate(XmlNode xn)
                                                           {
                                                               string name = xn.Attributes["name"].Value;
                                                               Version version = XmlParserUtil.ParseAttributeValue<Version>(
                                                                   xn.Attributes["version"],
                                                                   delegate(string s) { return new Version(s); });

                                                               return new CliEnvironment((CliType)Enum.Parse(typeof(CliType), name, true), version);
                                                           });
        }

        private IsaType[] ParseIsas(XmlNode componentNode, XmlNamespaceManager xmlNamespaceManager)
        {
            return XmlParserUtil.Parse<IsaType>(componentNode, "componento:isas/componento:isa", xmlNamespaceManager, 
                                                delegate(XmlNode xn)
                                                    {
                                                        return (IsaType)Enum.Parse(typeof(IsaType), xn.Attributes["name"].Value, true);
                                                    });
        }

        private string[] ParseLicenses(XmlNode componentNode, XmlNamespaceManager xmlNamespaceManager)
        {
            return XmlParserUtil.Parse<string>(componentNode, "componento:licenses/componento:license", xmlNamespaceManager, 
                                               delegate(XmlNode xn)
                                                   {
                                                       return xn.Attributes["name"].Value;
                                                   });
        }
    }
}